package com.gzwanchuang.lszg.module.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gzwanchuang.lszg.MainActivity;
import com.gzwanchuang.lszg.R;
import com.gzwanchuang.lszg.base.BaseActivity;
import com.gzwanchuang.lszg.base.MainApplication;
import com.gzwanchuang.lszg.help.UserBean;
import com.gzwanchuang.lszg.help.UserHelper;
import com.gzwanchuang.lszg.net.Apis;
import com.gzwanchuang.lszg.net.NetworkManager;
import com.gzwanchuang.lszg.net.WebApis;

import com.gzwanchuang.lszg.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.lszg.proto.Index;
import com.gzwanchuang.lszg.proto.LoginOuterClass;
import com.gzwanchuang.lszg.proto.MemberOuterClass;
import com.gzwanchuang.lszg.utils.APKVersionCodeUtils;
import com.gzwanchuang.lszg.utils.StatusBarUtil;
import com.gzwanchuang.lszg.web.ui.WebViewActivity;
import com.google.protobuf.InvalidProtocolBufferException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.phone_et)
    EditText loginAccountEdt;
    @BindView(R.id.password_et)
    EditText loginPwdEdt;
    @BindView(R.id.login_btn)
    Button loginBtn;
    @BindView(R.id.login_cb_password)
    CheckBox loginCbPassword;
    @BindView(R.id.tv_welcome)
    TextView tvWelcome;

    private long mExitTime;

    private int isrenzheng = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        StatusBarUtil.setTranslucentStatus(this);
        ButterKnife.bind(this);
        tvWelcome.setText("Hi，欢迎登录" + getString(R.string.app_name));
        setPasswordCanSee();
        setAccountEt();
        checkVersion();
    }

    private void setAccountEt() {
        loginPwdEdt.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                login();
                return true;
            }
            return false;
        });
        String phone = getIntent().getStringExtra("phone");
        if (!TextUtils.isEmpty(phone)) {
            loginAccountEdt.setText(phone);
            loginAccountEdt.setSelection(phone.length());//将光标移至文字末尾
        }
    }


    private void login() {
        String account = loginAccountEdt.getText().toString();
        if (TextUtils.isEmpty(account)) {
            showToast("请输入手机号");
            return;
        }
        String pwd = loginPwdEdt.getText().toString();
        if (TextUtils.isEmpty(pwd)) {
            showToast("请输入登录密码");
            return;
        }
        showProgress();
        LoginOuterClass.Login.Builder builder = LoginOuterClass.Login.newBuilder();
        builder.setUsername(account).setPassword(pwd).setClient("android");
        NetworkManager.INSTANCE.post(Apis.login, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                loginSuccess(LoginOuterClass.Login.parseFrom(bytes));
                identification();
            }

            @Override
            public void onError(int code, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    private void loginSuccess(LoginOuterClass.Login respon) {
        showToast("登录成功");
        UserBean userBean = new UserBean();
        userBean.setKey(respon.getKey());
        userBean.setChat_id(respon.getChatId());
        userBean.setChat_id(respon.getChatId());
        userBean.setChat_pwd(respon.getChatPwd());
        userBean.setPush_id(respon.getPushId());
        UserHelper.login(userBean);
    }

    /**
     * 设置密码是否为明文显示
     */
    private void setPasswordCanSee() {
        loginCbPassword.setOnCheckedChangeListener((compoundButton, isChecked) -> {
            if (isChecked) {
                //设置为密文显示
                loginPwdEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                //设置为明文显示
                loginPwdEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            //光标在最后显示
            loginPwdEdt.setSelection(loginPwdEdt.length());
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                MainApplication.finishAllActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 验证是否进行实名认证
     */
    private void identification() {
        NetworkManager.INSTANCE.post(Apis.memberDataInfo, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                hideProgress();
                MemberOuterClass.Member member = MemberOuterClass.Member.parseFrom(bytes);
                UserBean userBean = new UserBean();
                userBean.setIs_approve(member.getIsApprove());
                userBean.setIs_bank(member.getIsBank());
                userBean.setTruename(member.getTruename());
                UserHelper.syncCurrentUserInfo(userBean);
                if (member.getIsApprove() == isrenzheng) {
                    showToast("请先进行实名认证");
                    WebViewActivity.startActivity(mContext, WebApis.Verification);
                } else {
                    if (member.getIsBank() == 0) {

                        WebViewActivity.startActivity(mContext, WebApis.bindBankCard + "?user_name=" + member.getTruename());
                    } else {
                        startActivity(MainActivity.class);
                    }
                    finish();
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    /**
     * 检测版本更新
     */
    private void checkVersion() {
        Index.get_app_version_info.Builder builder = Index.get_app_version_info.newBuilder();
        builder.setClient("android");
        NetworkManager.INSTANCE.post(Apis.versionCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
                new APKVersionCodeUtils().checkVerison(response, mContext);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
            }
        });
    }


    @OnClick({R.id.login_btn, R.id.forget_password_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                isrenzheng = 0;
                login();
                break;
            case R.id.forget_password_tv:
                Intent intent = new Intent(mContext, ForgetPasswordActivity.class);
                intent.putExtra("title", "忘记密码");
                startActivityForResult(intent, 100);
                break;

        }
    }
}
